<template>
  <div ref="pieRef" :style="{ width: width, height: height, color: 'white' }">
  </div>
</template>
<script setup lang="ts">
import useChart from '@/hooks/useChart';
import type { EChartsOption } from 'echarts';
import { ref, watch } from 'vue';
const props = defineProps({
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '100%'
  },
  pieDatas: {
    type: Array<{
    value: number
    name: string
    percentage: string
    color: string
  }>,
    default: () => []
  }
})

const pieRef = ref()

// useChart hook只有在依赖的[响应式数据如ref、reactive]发生变化时才会执行
const { setChartOption } = useChart(pieRef, formatOptions(props.pieDatas))

// 饼图数据变化时，重新设置饼图数据
watch(() => props.pieDatas, () => {
  setChartOption(formatOptions(props.pieDatas))
})

function formatOptions(
  pieDatas: Array<{
    value: number
    name: string
    percentage: string
    color: string
  }>,
): EChartsOption {
  const colors = pieDatas.map((item) => {
    return item.color
  })

  const data = pieDatas.map((item) => {
    return {
      value: item.value,
      name: item.name,
    }
  })

  const total = pieDatas.reduce((a, b) => {
    return a + b.value * 1
  }, 0)

  const option: EChartsOption = {
    color: colors,
    title: {
      text: `{nameSty| 充电桩总数}\n{number|${total}}`,
      top: '50%',
      left: '30%',
      textStyle: {
        rich: {
          nameSty: {
            fontSize: 19,
            color: 'white',
            padding: [10, 0],
          },
          number: {
            fontSize: 24,
            color: 'white',
            padding: [4, 0, 0, 20],
          },
        },
      },
    },
    legend: {
      orient: 'vertical',
      right: '10%',
      top: '18%',
      itemGap: 20,
      itemWidth: 16,
      itemHeight: 16,
      icon: 'rect',
      formatter: function (name: string) {
        const currentItem = pieDatas.find((item) => item.name === name)
        return (
          '{nameSty|' +
          currentItem?.name +
          '}\n' +
          '{numberSty|' +
          currentItem?.value +
          '个 }' +
          '{preSty|' +
          currentItem?.percentage +
          '}'
        )
      },
      textStyle: {
        rich: {
          nameSty: {
            fontSize: 12,
            color: '#FFFFFF',
            padding: [10, 14],
          },
          numberSty: {
            fontSize: 12,
            color: '#40E6ff',
            padding: [0, 0, 0, 14],
          },
          preSty: {
            fontSize: 12,
            color: '#40E6ff',
          },
        },
      },
    },
    series: [
      {
        type: 'pie',
        center: ['40%', '57%'],
        radius: ['30%', '75%'],
        label: {
          show: false,
        },
        data: data,
        roseType: 'area',
      },
    ],
  }
  return option
}
</script>
<style scoped></style>